import { setCookie } from '@/utils/cookie'
import { nextTick } from 'vue'
import { createI18n, I18n, UseI18nOptions, useI18n } from 'vue-i18n'

export const I18N_LANGUAGE_KEY = 'language'

export const LanguageEnums = Object.freeze({
  EN: 'en',
  ZH: 'zh-CN',
  JA: 'ja',
})
export const LanguageNameMap = Object.freeze({
  [LanguageEnums.EN]: 'language.en',
  [LanguageEnums.ZH]: 'language.zh-CN',
  [LanguageEnums.JA]: 'language.ja',
})

export const SUPPORT_LOCALES: string[] = Object.values(LanguageEnums)

export function setupI18n(
  options: UseI18nOptions = {
    locale: localStorage.getItem(I18N_LANGUAGE_KEY) || LanguageEnums.ZH,
    fallbackWarn: false,
    missingWarn: false,
  }
): I18n {
  const i18n = createI18n({ legacy: false, ...options })
  loadLocaleMessages(i18n, options.locale!)
  setI18nLanguage(i18n, options.locale!)

  return i18n
}

export function setI18nLanguage(i18n: I18n, locale: string) {
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale
  } else {
    // @ts-ignore
    i18n.global.locale.value = locale
  }

  localStorage.setItem(I18N_LANGUAGE_KEY, locale)
  document.querySelector('html')?.setAttribute('lang', locale)
}

export async function loadLocaleMessages(i18n: I18n, locale: string) {
  const messages = await import(`./locales/${locale}.json`)
  i18n.global.setLocaleMessage(locale, messages.default)

  return nextTick()
}

export const i18n = setupI18n()
